package com.cjx.auth.domian;

import cn.hutool.core.collection.CollectionUtil;
import com.cjx.admin.dto.AdminUserDTO;
import com.cjx.admin.dto.AdminUserInfoDTO;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.ArrayList;
import java.util.Collection;

/**
*@Description security的user类
*@Verson v1.0.0
*@Author cjunxian
*@Date 
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class SecurityUser implements UserDetails {

    /**
     * ID
     */
    private String id;
    /**
     * 用户名
     */
    private String username;
    /**
     * 用户密码
     */
    private String password;
    /**
     * 用户状态
     */
    private Boolean enabled = true;
    /**
     * 登录客户端ID
     */
    private String clientId;

    /**
     * 账号是否已经过期
     */
    private Boolean accountExpired = false;

    /**
     * 是否锁定
     */
    private Boolean locked = false;

    /**
     * 凭证是否已过期
     */
    private Boolean credentialsExpired = false;

    /**
     * 权限数据
     */
    private Collection<SimpleGrantedAuthority> authorities;

    public SecurityUser(AdminUserInfoDTO userDTO){
        this.setId(userDTO.getId());
        this.setUsername(userDTO.getUsername());
        this.setPassword(userDTO.getPassword());
        this.setEnabled(userDTO.getEnabled().equals(0)?false:true);
        this.setClientId(userDTO.getClientId());
        if(CollectionUtil.isNotEmpty(userDTO.getRoles())){
            authorities = new ArrayList<>();
            userDTO.getRoles().forEach(role -> authorities.add(new SimpleGrantedAuthority(role.getId())));
        }
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return this.authorities;
    }

    @Override
    public String getPassword() {
        return this.password;
    }

    @Override
    public String getUsername() {
        return this.username;
    }

    @Override
    public boolean isAccountNonExpired() {
        return !this.accountExpired;
    }

    @Override
    public boolean isAccountNonLocked() {
        return !this.locked;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return !this.credentialsExpired;
    }

    @Override
    public boolean isEnabled() {
        return this.enabled;
    }
}
